package br.edu.ufcg.dsc.psoo.mymoney.view.action;

import org.mentawai.core.BaseAction;
import org.mentawai.filter.AuthenticationFree;
import org.mentawai.filter.RedirectAfterLogin;
import org.mentawai.rule.EmailRule;
import org.mentawai.rule.EqualRule;
import org.mentawai.rule.RegexRule;
import org.mentawai.validation.Validatable;
import org.mentawai.validation.Validator;

import br.edu.ufcg.dsc.psoo.mymoney.controller.UserController;
import br.edu.ufcg.dsc.psoo.mymoney.controller.exceptions.InvalidUserException;
import br.edu.ufcg.dsc.psoo.mymoney.controller.implementation.UserControllerImpl;
import br.edu.ufcg.dsc.psoo.mymoney.model.bean.User;
import br.edu.ufcg.dsc.psoo.mymoney.model.dao.AccountDAO;
import br.edu.ufcg.dsc.psoo.mymoney.model.dao.UserDAO;

public class UserAction extends BaseAction implements Validatable, AuthenticationFree, RedirectAfterLogin {
	
	private UserDAO userDAO;
	private AccountDAO accountDAO;
	private UserController controller;
	
//	private BeanSession getBeanSession() {
//		
//		return (BeanSession) input.getValue("beanSession");
//	}
//	
	
	public void setUserDAO(UserDAO userDAO) {
		   this.userDAO = userDAO;
	   }
	   //TODO javadoc
	   public void setAccountDAO(AccountDAO accountDAO) {
		   this.accountDAO = accountDAO;
	   }
	   
	   public void initiate() {
		   if (controller == null)
				controller = new UserControllerImpl(userDAO,accountDAO);
	   }

	// You don't need to log to register...
	public boolean bypassAuthentication(String innerAction) {
		
		if (innerAction != null && innerAction.equals("add")) return true;
		
		return false;
	}
	
	public boolean shouldRedirect(String innerAction) {
		
		if (innerAction != null && innerAction.equals("edit")) return true;
		
		return false;
	}
	
	public void prepareValidator(Validator val, String innerAction) {
		
		if (innerAction != null && innerAction.equals("add") && isPost()) {
			
			val.requiredFields("Campo obrigatorio!", "username", "password", "email" , "confirmation");
			
			val.add("username", RegexRule.getInstance("^[A-Za-z][A-Za-z0-9\\-\\_\\.]*[A-Za-z0-9]$"), "Username invalido!");
			
			val.add("email", EmailRule.getInstance(), "Email invalido!");
			
			val.add("password", EqualRule.getInstance("password", "passconf"), "As senhas nao conferem!");
			
		} else if (innerAction != null && innerAction.equals("edit") && isPost()) {

			val.requiredFields("Campo obrigatorio!", "username", "email");
			
			val.add("username", RegexRule.getInstance("^[A-Za-z][A-Za-z0-9\\-\\_\\.]*[A-Za-z0-9]$"), "Username invalido!");
			
			val.add("email", EmailRule.getInstance(), "Email invalido!");
		}
		
	}
	
	public String add() {
		initiate();
		if (!isPost()) {
			
			return ERROR;
			
		} else {
			
			User u = input.getObject(User.class);
			User newUser = null;
			try {
				newUser = controller.create(u);
			} catch (InvalidUserException e) {
				addError("username", e.getMessage());
				return ERROR;
			}
			
			//loga novo usuário na sessão atual
			setUserSession(newUser);
			
			addMessage("Seu cadastro foi efetuado com sucesso!");
			
			return CREATED;
		}
	}
	
	public String edit() {
		initiate();
		if (!isPost()) {
			
			// display user for update...
			
			User u = (User) getUserSession();
			
			output.setValue("user", u);
			
			return SHOW;
			
		} else {
			
			User newUser = input.getObject(User.class);
			
			User loggedUser = (User) getUserSession();
			
			newUser.setId(loggedUser.getId());
			
			try {
				newUser = controller.update(newUser);
			} catch (InvalidUserException e) {
				addError("defaultError", e.getMessage());
				return ERROR;
			}
			
			replaceUserSession(newUser);
			
			addMessage("Informacoes alteradas com sucesso!");
			
			return UPDATED;
		}
	}
	
	
}